package com.zretc.emptraining.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.zretc.emptraining.dbtools.PageData;
import com.zretc.emptraining.dbtools.AjaxResponse;
import com.zretc.emptraining.entity.Teach;
import com.zretc.emptraining.service.TeachService;
import com.zretc.emptraining.serviceimpl.TeachServiceImpl;

/**
 * Servlet implementation class TeachServlet
 */
@WebServlet("/TeachServlet")
public class TeachServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	TeachService tsi = new TeachServiceImpl();

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TeachServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("".equals(op)) {
			showAll(request, response);
		} else if ("add".equals(op)) {
			addTeach(request, response);
		} else if ("del".equals(op)) {
			delTeach(request, response);
		} else if ("updpic".equals(op)) {
			updPic(request, response);
		} else if ("updinfo".equals(op)) {
			updInfo(request, response);
		} else if ("delAll".equals(op)) {
			delAll(request, response);
		} else if ("ajaxReq".equals(op)) {
			// 获得所有教员信息
			doAjaxReq(request, response);
		} else if ("info".equals(op)) {
			// 获得单个教员信息
			getSingleInfo(request, response);
		} else if ("updinfos".equals(op)) {
			// 前台修改教员信息
			updSingleInfo(request, response);
		}
	}

	// 前台修改教员信息
	private void updSingleInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String teacherTel = request.getParameter("teacherTel");
		String dsc = request.getParameter("teacherDesc");
		String teacherPic = request.getParameter("teacherPic");
		System.out.println("dsc:" + dsc);
		System.out.println("teacherTel:" + teacherTel);
		boolean flag = tsi.updInfoByDesc(teacherTel, dsc, teacherPic);
		String msg = "修改成功";
		if (!flag) {
			msg = "修改失败";
		}
		Gson gson = new Gson();
		String toJson = gson.toJson(msg);
		PrintWriter printWriter = response.getWriter();
		printWriter.print(toJson);
		printWriter.close();
	}

	// 获得单个教员信息
	private void getSingleInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取session
		// 获取session传过来的值
		String teacherTel = request.getParameter("username");
		List<Teach> pd = tsi.getTeachByTel(teacherTel);
		System.out.println(teacherTel);
		request.setAttribute("pd", pd);
		request.getRequestDispatcher("TeacherInfo.jsp").forward(request, response);
	}

	private void delAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String s = request.getParameter("r");
		s = s.substring(0, s.length() - 1);
		String[] strs = s.split(",");
		boolean flag = false;
		String msg = "删除失败!";
		int code = 0;
		for (int i = 0; i < strs.length; i++) {
			flag = tsi.delTeach(Integer.parseInt(strs[i]));
		}
		if (flag) {
			msg = "删除成功!";
			code = 200;
		}
		Gson(msg, code, response);
	}

	private void updInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("到了修改页面");
		int teacherNo = Integer.parseInt(request.getParameter("teacherNo"));
		String teacherName = request.getParameter("teacherName");
		String teacherSex = request.getParameter("teacherSex");
		String teacherXl = request.getParameter("teacherXl");
		String teacherTel = request.getParameter("teacherTel");
		String teacherDesc = request.getParameter("teacherDesc");
		Teach teach = new Teach(teacherNo, teacherName, teacherSex, teacherXl, teacherTel, teacherDesc);
		boolean flag = tsi.updInfo(teach);
		System.out.println(flag);
		String msg = "修改失败!";
		int code = 0;
		if (flag) {
			msg = "修改成功!";
			code = 200;
		}
		Gson(msg, code, response);
	}

	private void updPic(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("到了修改页面");
		int teacherNo = Integer.parseInt(request.getParameter("teacherNo"));
		String PicPath = "";
		String teacherPic = "";
		if (request.getAttribute("filename") != null) {
			PicPath = (String) request.getAttribute("filename");
			teacherPic = "upload/" + PicPath;
		}
		if (request.getAttribute("filename") == null) {
			teacherPic = request.getParameter("teacherPic");
		}
		Teach teach = new Teach(teacherNo, teacherPic);
		String jsonResponse = "{\"code\":0}";
		boolean flag = tsi.updPic(teach);
		if (flag) {
			jsonResponse = "{\"code\":200}";
		}
		System.out.println("jsonResponse:" + jsonResponse);
		Gson gson = new Gson();
		String listCourses = gson.toJson(jsonResponse);
		// 4 响应
		PrintWriter out = response.getWriter();
		out.print(listCourses);
		// 5.关闭
		out.close();
	}

	private void delTeach(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("到了删除页面");
		int teachNo = 0;
		if (request.getParameter("teachNo") != null) {
			teachNo = Integer.parseInt(request.getParameter("teachNo"));
		}
		System.out.println(teachNo);
		boolean flag = tsi.delTeach(teachNo);
		System.out.println(flag);
		String msg = "删除失败";
		int code = 0;
		if (flag) {
			msg = "删除成功";
			code = 200;
		}
		Gson(msg, code, response);
	}

	private void addTeach(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String teacherName = request.getParameter("teacherName");
		String teacherSex = request.getParameter("teacherSex");
		String teacherXl = request.getParameter("teacherXl");
		String teacherTel = request.getParameter("teacherTel");
		String teacherDesc = request.getParameter("teacherDesc");
		String PicPath = (String) request.getAttribute("filename");
		String teacherPic = "upload/" + PicPath;
		Teach teach = new Teach(0, teacherName, teacherSex, teacherXl, teacherTel, teacherDesc, teacherPic);
		String jsonResponse = "{\"code\":0}";
		boolean flag = tsi.addTeach(teach);
		if (flag) {
			jsonResponse = "{\"code\":200}";
		}
		System.out.println("json:" + jsonResponse);
		// 3将list转换为JSON格式的字符串
		Gson gson = new Gson();
		String listCourses = gson.toJson(jsonResponse);
		// 4 响应
		PrintWriter out = response.getWriter();
		out.print(listCourses);
		// 5.关闭
		out.close();

	}

	private void showAll(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("显示");
		int page = 1;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		int pageSize = 10;
		if (request.getParameter("pageSize") != null) {
			page = Integer.parseInt(request.getParameter("pageSize"));
		}
		String keyword = "";
		if (request.getParameter("keyword") != null) {
			keyword = request.getParameter("keyword");
		}
		PageData<Teach> pd = null;
		// 获取查询对象
		String selectKey = "教员名";
		if (request.getParameter("selectKey") != null) {
			selectKey = request.getParameter("selectKey");
		}
		// 当选择教员名或者输入为空时或者没有选择时
		if (selectKey.equals("教员名") || keyword.equals("")) {
			pd = tsi.getPageByTeachName(page, pageSize, keyword);
		} else if (selectKey.equals("教员号")) {
			pd = tsi.getPageByteachNo(page, pageSize, keyword);
		} else if (selectKey.equals("性别")) {
			pd = tsi.getPageByteachSex(page, pageSize, keyword);
		} else if (selectKey.equals("学历")) {
			pd = tsi.getPageByteachXl(page, pageSize, keyword);
		}
		request.setAttribute("pd", pd);
		request.setAttribute("keyword", keyword);
		request.setAttribute("selectKey", selectKey);

		request.getRequestDispatcher("TeachList.jsp").forward(request, response);
	}

	/**
	 * 处理AJAX请求，获得所有教员
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void doAjaxReq(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		// 2 调用 service的方法
		List<Teach> list = tsi.getAllTeachers();
		// 3将list转换为JSON格式的字符串
		Gson gson = new Gson();
		String listCourses = gson.toJson(list);
		// 4 响应
		PrintWriter out = response.getWriter();
		out.print(listCourses);
		// 5.关闭
		out.close();
	}

	public void Gson(String msg, int code, HttpServletResponse response) throws IOException {
		Gson gson = new Gson();
		AjaxResponse ajaxres = new AjaxResponse(msg, code);
		String jsonString = gson.toJson(ajaxres);
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		outPrintWriter.close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
